package org.tobie.order.controller;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.common.uaa.entity.UserEntity;
import com.common.utils.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.tobie.order.config.AliPayConfig;
import org.tobie.order.dto.AliPay;
import org.tobie.order.mapper.OrderDao;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: lzd
 * TODO
 * 2023/10/20 15:55
 */
@RestController
@CrossOrigin
@RequestMapping("/alipay")
@Slf4j
public class AlipayController {
    private static final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private static final String FORMAT = "JSON";
    private static final String CHARSET = "UTF-8";
    //签名方式
    private static final String SIGN_TYPE = "RSA2";

    @Resource
    private AliPayConfig aliPayConfig;
    @Resource
    private OrderDao ordersDao;
    /**
     *跳转到支付宝提供的沙盒页面
     */
    @RequestMapping("/pay") // ?subject=xxx&traceNo=xxx&totalAmount=xxx
    public void pay(AliPay aliPay, HttpServletResponse httpResponse) throws Exception {
        // 1. 创建Client，通用SDK提供的Client，负责调用支付宝的API
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);

        // 2. 创建 Request并设置Request参数
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();  // 发送请求的 Request类
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.set("out_trade_no", aliPay.getTraceNo());  // 我们自己生成的订单编号
        bizContent.set("total_amount", aliPay.getTotalAmount()); // 订单的总金额
        bizContent.set("subject", aliPay.getSubject());   // 支付的名称
        bizContent.set("product_code", "FAST_INSTANT_TRADE_PAY");  // 固定配置
        request.setBizContent(bizContent.toString());

        // 执行请求，拿到响应的结果，返回给浏览器
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }
    /**
     *沙盒回调请求
     */
    @PostMapping("/return")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        return "success";
    }
    /**
     * 保存支付订单
     */
    @RequestMapping("/saveList/{subject}/{tradeNo}/{totalAmount}")
    public ResultVo<String> saveList(@PathVariable("subject") String subject, @PathVariable("tradeNo") String tradeNo, @PathVariable("totalAmount") String totalAmount) throws ParseException {
        SecurityContext context = SecurityContextHolder.getContext();
        Authentication authentication = context.getAuthentication();
        UserEntity userEntity = (UserEntity) authentication.getPrincipal();
        String uerAccount = userEntity.getUsername();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date payTime = sdf.parse(sdf.format(Long.valueOf(tradeNo)));
        if(ordersDao.saveList(subject, tradeNo, totalAmount,payTime,uerAccount)) {
            return ResultVo.success("保存成功");
        }else{
            return ResultVo.fail("保存失败");
        }
    }
//    /**
//     *获取某个用户全部订单
//     */
//    @RequestMapping("/getOrders/{pageNum}")
//    public ResultVo<List<OrdersEntity>> getOrders(@RequestHeader String token,@PathVariable("pageNum") Integer pageNum){
//        String userAccount = TokenUtil.getLoginName(token);
//        PageHelper.startPage(pageNum, 5);
//        List<OrdersEntity> ordersEntities = ordersDao.getOrders(userAccount);
//        return ResultVo.success(ordersEntities);
//    }
//    /**
//     *订单搜索
//     */
//    @RequestMapping("/findMsg/{selectMsg}/{pageNum}")
//    public ResultVo<List<OrdersEntity>> findMsg(@RequestHeader String token,@PathVariable("selectMsg") String selectMsg,@PathVariable("pageNum") Integer pageNum){
//        String userAccount = TokenUtil.getLoginName(token);
//        PageHelper.startPage(pageNum, 5);
//        List<OrdersEntity> ordersEntities = ordersDao.findMsg(selectMsg,userAccount);
//        return  ResultVo.success(ordersEntities);
//    }
//    /**
//     *获取订单页最大页码
//     */
//    @RequestMapping("/getMaxPageNum")
//    public ResultVo<Integer> getMaxPageNum(@RequestHeader String token){
//        String userAccount = TokenUtil.getLoginName(token);
//        int count = ordersDao.getMaxPageNum(userAccount);
//        if(count%5==0){
//            return ResultVo.success(count/5);
//        }else{
//            return ResultVo.success((count/5)+1);
//        }
//    }
}
